<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import type { Ref } from 'vue'
import OR_new_place_app from './OR_new_place_app.vue'

const emit = defineEmits(['navigate-to-applications'])

// 定义场地数据结构
interface Place {
  plId: number
  plName: string
  plPicture: string
  plAddress: string
  plCreateTime: string
  plMaxPeople: number
  isUsing: number
  plInfo: string
}

// 响应式数据
const places: Ref<Place[]> = ref([])
const loading: Ref<boolean> = ref(true)
const error: Ref<string | null> = ref(null)
const currentPage: Ref<number> = ref(1)
const pageSize: Ref<number> = ref(2)
const filterStatus: Ref<number | null> = ref(null) // null表示全部
const showApplicationForm: Ref<boolean> = ref(false)
const selectedPlace: Ref<Place | null> = ref(null)

// 获取场地列表数据
const fetchPlaces = async () => {
  try {
    loading.value = true
    error.value = null
    
    // 从 localStorage 获取 token
    const token = localStorage.getItem('token')
    
    if (!token) {
      throw new Error('未找到身份凭证，请重新登录')
    }
    
    // 发送 GET 请求获取数据
    const response = await fetch('http://localhost:8080/place/list', {
      method: 'GET',
      headers: {
        'token': token,
        'Content-Type': 'application/json'
      }
    })
    
    const result = await response.json()
    
    if (result.msg === '获取成功') {
      places.value = result.data
    } else {
      throw new Error(result.msg || '获取数据失败')
    }
  } catch (err) {
    console.error('获取场地列表数据失败:', err)
    error.value = err instanceof Error ? err.message : '获取数据失败'
  } finally {
    loading.value = false
  }
}

// 计算过滤后的数据
const filteredPlaces = computed(() => {
  if (filterStatus.value === null) {
    return places.value
  }
  return places.value.filter(place => place.isUsing === filterStatus.value)
})

// 计算当前页的数据
const paginatedPlaces = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredPlaces.value.slice(start, end)
})

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(filteredPlaces.value.length / pageSize.value)
})

// 使用状态文本映射
const getUsingStatusText = (status: number) => {
  return status === 1 ? '使用中' : '未使用'
}

// 使用状态样式映射
const getUsingStatusClass = (status: number) => {
  return status === 1 ? 'status-using' : 'status-not-using'
}

// 租借按钮状态样式映射
const getRentButtonClass = (status: number) => {
  return status === 1 ? 'rent-button-active' : 'rent-button-inactive'
}

//////////////////////////////////////////
// 获取图片完整路径
const getImageUrl = (picturePath: string) => {
  // 如果没有图片路径，返回空字符串
  if (!picturePath) return ''
  
  // 如果已经是完整URL，直接返回
  if (picturePath.startsWith('http')) {
    return picturePath
  }
  
  // 如果是绝对路径形式，拼接基础路径
  if (picturePath.startsWith('/')) {
    return `http://localhost:8080${picturePath}`
  }
  
  // 其他情况，也拼接基础路径
  return `http://localhost:8080/${picturePath}`
}
////////////////////////////////////////

// 页面切换
const goToPage = (page: number) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
  }
}

// 筛选状态
const setFilter = (status: number | null) => {
  filterStatus.value = status
  currentPage.value = 1 // 重置到第一页
}

// 导航到申请页面并传递数据
const navigateToApplications = () => {
  // 将场地数据存储到 sessionStorage 中
  sessionStorage.setItem('placesData', JSON.stringify(places.value));
  emit('navigate-to-applications');
}

// 打开租借申请表单
const openApplicationForm = (place: Place) => {
  if (place.isUsing === 1) {
    selectedPlace.value = place
    showApplicationForm.value = true
  }
}

// 关闭租借申请表单
const closeApplicationForm = () => {
  showApplicationForm.value = false
  selectedPlace.value = null
}

// 处理租借申请提交
const handleApplicationSubmit = (applicationData: any) => {
  // 这里应该发送申请数据到后端
  console.log('提交租借申请:', applicationData)
  alert('场地租借申请已提交')
  closeApplicationForm()
}

// 组件挂载时获取数据
onMounted(() => {
  fetchPlaces()
})
</script>

<template>
  <div class="place-container">
    <!-- 申请表单视图 -->
    <div v-if="showApplicationForm && selectedPlace" class="application-form-view">
      <OR_new_place_app 
        :place="selectedPlace" 
        @cancel="closeApplicationForm"
        @submit="handleApplicationSubmit"
      />
    </div>
    
    <!-- 场地列表视图 -->
    <div v-else>
      <!-- 顶部按钮区域 -->
      <div class="header-buttons">
        <!-- 筛选按钮 -->
        <div class="filter-buttons">
          <button 
            :class="{ active: filterStatus === null }"
            @click="setFilter(null)"
            class="filter-button"
          >
            全部
          </button>
          <button 
            :class="{ active: filterStatus === 1 }"
            @click="setFilter(1)"
            class="filter-button"
          >
            使用中
          </button>
          <button 
            :class="{ active: filterStatus === 0 }"
            @click="setFilter(0)"
            class="filter-button"
          >
            暂停使用
          </button>
        </div>
        
        <!-- 新建申请按钮 -->
        <button 
          @click="navigateToApplications"
          class="new-application-button"
        >
          场地申请情况
        </button>
      </div>
      
      <!-- 加载状态 -->
      <div v-if="loading" class="loading">
        数据加载中...
      </div>
      
      <!-- 错误状态 -->
      <div v-else-if="error" class="error">
        {{ error }}
      </div>
      
      <!-- 数据展示 -->
      <div v-else class="places-container">
        <div class="places-list">
          <div 
            v-for="place in paginatedPlaces" 
            :key="place.plId" 
            class="place-card"
          >
            <div class="card-header">
              <h3>{{ place.plName }}</h3>
              <span 
                class="status-badge" 
                :class="getUsingStatusClass(place.isUsing)"
              >
                {{ getUsingStatusText(place.isUsing) }}
              </span>
            </div>
            
            <div class="card-body">
              <!-- 图片展示区域 -->
              <div class="image-container">
                <img 
                  v-if="place.plPicture" 
                  :src="getImageUrl(place.plPicture)" 
                  :alt="place.plName"
                  class="place-image"
                  @error="($event) => { ($event.target as HTMLImageElement).src = ''; }"
                >
                <div v-else class="no-image">
                  无图片
                </div>
              </div>
              
              <!-- 场地信息区域 -->
              <div class="info-container">
                <div class="info-row">
                  <span class="label">地址:</span>
                  <span>{{ place.plAddress }}</span>
                </div>
                
                <div class="info-row">
                  <span class="label">创建时间:</span>
                  <span>{{ new Date(place.plCreateTime).toLocaleString() }}</span>
                </div>
                
                <div class="info-row">
                  <span class="label">最大容纳人数:</span>
                  <span>{{ place.plMaxPeople }}人</span>
                </div>
                
                <div class="info-row">
                  <span class="label">描述:</span>
                  <span>{{ place.plInfo }}</span>
                </div>
                
                <!-- 租借按钮 -->
                <div class="rent-button-container">
                  <button
                    :class="['rent-button', getRentButtonClass(place.isUsing)]"
                    @click="openApplicationForm(place)"
                    :disabled="place.isUsing !== 1"
                  >
                    租借场地
                  </button>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 无数据提示 -->
          <div v-if="filteredPlaces.length === 0" class="no-data">
            暂无场地数据
          </div>
        </div>
        
        <!-- 分页控件 -->
        <div v-if="filteredPlaces.length > 0" class="pagination">
          <button 
            :disabled="currentPage === 1" 
            @click="goToPage(currentPage - 1)"
            class="page-button"
          >
            上一页
          </button>
          
          <span class="page-info">
            第 {{ currentPage }} 页，共 {{ totalPages }} 页
          </span>
          
          <button 
            :disabled="currentPage === totalPages" 
            @click="goToPage(currentPage + 1)"
            class="page-button"
          >
            下一页
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.place-container {
  width: 95%;
  padding: 20px;
}

.place-container h2 {
  color: #333;
  font-size: 2rem;
  margin-bottom: 20px;
  text-align: center;
}

.header-buttons {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.new-application-button {
  padding: 8px 16px;
  background-color: #31B310;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.new-application-button:hover {
  background-color: #2a990e;
}

.filter-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.filter-button {
  padding: 8px 16px;
  background-color: #ecf0f1;
  color: #333;
  border: 1px solid #bdc3c7;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.filter-button:hover {
  background-color: #d6dbdf;
}

.filter-button.active {
  background-color: #3498db;
  color: white;
  border-color: #3498db;
}

.loading, .error, .no-data {
  text-align: center;
  padding: 40px 20px;
  font-size: 1.2rem;
}

.error {
  color: #e74c3c;
}

.no-data {
  color: #7f8c8d;
}

.places-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.places-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}

.place-card {
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 20px;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.card-header h3 {
  margin: 0;
  color: #333;
}

.status-badge {
  padding: 5px 10px;
  border-radius: 20px;
  font-size: 0.8rem;
  font-weight: bold;
}

.status-using {
  background-color: #27ae60;
  color: white;
}

.status-not-using {
  background-color: #e74c3c;
  color: white;
}

.card-body {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.place-content {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.image-container {
  width: 100%;
}

.place-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 8px;
}

.no-image {
  width: 100%;
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  border: 1px dashed #ddd;
  border-radius: 8px;
  color: #999;
}

.info-container {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.info-row {
  display: flex;
  flex-wrap: wrap;
  font-size: 1rem; /* 减小描述信息的字号 */
}

.label {
  font-weight: bold;
  min-width: 120px;
  margin-right: 10px;
  color: #555;
}

.rent-button-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 15px;
}

.rent-button {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
}

.rent-button-active {
  background-color: #3498db;
  color: white;
}

.rent-button-active:hover {
  background-color: #2980b9;
}

.rent-button-inactive {
  background-color: #bdc3c7;
  color: #7f8c8d;
  cursor: not-allowed;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  padding: 20px 0;
}

.page-button {
  padding: 8px 16px;
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.page-button:disabled {
  background-color: #bdc3c7;
  cursor: not-allowed;
}

.page-button:hover:not(:disabled) {
  background-color: #2980b9;
}

.page-info {
  font-weight: bold;
  color: #333;
}
</style>